<template>
    <div class="task-manage page-container">
      <el-form class="query-form"
        ref="queryForm"
        :model="queryParams"
        :inline="true"
        size="small"
        label-width="">
        <el-form-item class="big-query" label="关键词"
          prop="keyword">
          <el-input v-model="queryParams.keyword"
            placeholder="请输入关键词"
            clearable
            size="small"
            style="width: 240px"
            @keyup.enter.native="handleQuery"
            @clear="handleQuery" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary"
            size="small"
            @click="handleQuery">搜索</el-button>
          <el-button size="small"
            @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
      <div class="operate-wrap">
        <el-button type="primary" @click.stop="openTaskDialog()"  size="small" icon="el-icon-plus">新增</el-button>
      </div>
      <el-table v-loading="loading" :data="taskList">
        <el-table-column label="活动名称"  width="180" prop="name" align="center"/>
        <el-table-column label="活动项目" width="180" prop="appid" align="center">
          <template slot-scope="scope">
           <span>{{getCurrentAppName(scope.row.appid)}}</span>
          </template>
        </el-table-column>
        <el-table-column label="活动类型" prop="type" align="center">
          <template slot-scope="scope">
           <span>{{getCurrentTaskType(scope.row.type)}}</span>
          </template>
        </el-table-column>
        <el-table-column label="分类图标" width="100" align="center">
          <template slot-scope="scope">
            <el-image slot="reference"
              style="height: 36px;cursor: pointer;"
              :src="scope.row.icon"
              fit="contain"></el-image>
          </template>
        </el-table-column>
        <el-table-column label="活动描述" prop="desc" align="center" />
        <el-table-column label="状态" width="100" prop="status" align="center">
          <template slot-scope="scope">
           <span>{{getCurrentTaskStatus(scope.row.status)}}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="操作"
          width="250"
          align="center">
          <template slot-scope="scope">
            <el-button type="text" size="small" v-if="scope.row.status === 'published'" @click.stop="updateTaskGroupStatus(scope.row, 'draft')">下架</el-button>
            <el-button type="text" size="small" v-if="scope.row.status !== 'published'" @click.stop="updateTaskGroupStatus(scope.row, 'published')">发布</el-button>
            <el-button type="text" size="small" @click.stop="openTaskDialog(scope.row)">修改</el-button>
            <el-button type="text" size="small" @click.stop="updateTaskGroupStatus(scope.row,'deleted')">删除</el-button>
            <el-button type="text" size="small" @click.stop="toDetail(scope.row)">活动详情</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination-wrap">
        <pagination v-show="total > 0"
        :total="total"
        :page.sync="queryParams.page"
        :limit.sync="queryParams.page_size"
        @pagination="getTableList" />
      </div>
      <el-dialog
        class="add-task-dialog"
        :title="form.group_id ? '编辑活动任务':'新增活动任务'"
        :visible.sync="dialogVisible"
        width="600px"
        :close-on-click-modal="false"
        @closed="reset">
        <el-form ref="form" :model="form" :rules="rules" label-width="80px">
          <el-form-item label="活动ID" prop="group_id">
            <el-input v-model="form.group_id" readonly></el-input>
          </el-form-item>
          <el-form-item label="活动名称" prop="name">
            <el-input v-model.trim="form.name" :maxLength="30"></el-input>
          </el-form-item>
          <el-form-item label="活动描述" prop="desc">
            <el-input v-model.trim="form.desc" :maxLength="100"></el-input>
          </el-form-item>
          <el-form-item label="活动图标" prop="icon">
            <ImgUpload v-model="form.icon"/>
          </el-form-item>
          <el-form-item label="活动类型" prop="type">
            <el-select v-model="form.type" placeholder="请选择活动类型">
               <el-option v-for="(value,key) in taskTypes" :key="key" :label="value" :value="key"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="有效期" prop="time">
            <el-date-picker v-model="form.time"
                type="datetimerange"
                align="right"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                :default-time="['00:00:00', '23:59:59']"
                value-format="yyyy-MM-dd HH:mm:ss"
                :picker-options="pickerOptions">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="项目" prop="appid">
            <!-- <select-check-box v-model="form.appid"
                :selOptions="permission_projectList"
                :props="{value: 'app_id', label: 'name'}"
                style="width:250px">
            </select-check-box> -->
            <el-select v-model="form.appid" placeholder="请选择项目">
               <el-option v-for="item in permission_projectList"
               :key="item.app_id"
               :label="item.name"
               :value="item.app_id"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="任务" prop="task_id">
            <el-select v-model="form.task_id" placeholder="请选择任务"
               multiple
               filterable
               remote
               :remote-method="getTaskList">
               <el-option v-for="item in taskOptionList.filter(item => item.status === 'published')" :key="item.id" :label="item.name" :value="item.task_id"></el-option>
            </el-select>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button type="primary" @click="addTaskGroup">确 定</el-button>
          <el-button @click="dialogVisible = false">取 消</el-button>
        </span>
      </el-dialog>
      <el-drawer
        :visible.sync="drawer"
        title="活动详情"
        size="calc(100% - 256px)"
        direction="rtl">
        <detail :currentId="currentId"></detail>
      </el-drawer>
    </div>
</template>
<script>
import { mapGetters } from 'vuex'
import ImgUpload from '@/components/img-upload'
import { addTaskGroup, getTaskList, getTaskGroupList, updateTaskGroup } from '@/api/task'
import { parseTime } from '@/utils'
import detail from './components/detail'
export default {
  data () {
    return {
      queryParams: {
        page: 1,
        page_size: 10,
        keyword: ''
      },
      taskTypes: {
        'fission': '裂变活动'
      },
      taskOptionList: [],
      statusDict: {
        'draf': '上架',
        'published': '发布',
        'deleted': '删除',
        'draft': '下架',
        'expire': '已过期',
        'not_start': '活动未开始'
      },
      total: 0,
      taskList: [],
      currentPage: 1,
      dialogVisible: false,
      loading: false,
      form: {
        group_id: '',
        name: '',
        desc: '',
        type: 'fission',
        appid: '',
        task_id: [],
        status: 'draft',
        icon: '',
        time: []
      },
      rules: {
        name: [
          { required: true, message: '请填写活动名称', trigger: 'change' }
        ],
        desc: [
          { required: true, message: '请填写活动描述', trigger: 'change' }
        ],
        type: [
          { required: true, message: '请选择活动类型', trigger: 'change' }
        ],
        icon: [
          { required: true, message: '请选择活动图标', trigger: 'change' }
        ],
        appid: [
          { required: true, message: '请选择项目', trigger: 'change' }
        ],
        time: [
          { required: true, message: '请选择活动有效期', trigger: 'change' }
        ],
        task_id: [
          { required: true, message: '请选择任务', trigger: 'change' }
        ]
      },
      drawer: false,
      currentId: '',
      pickerOptions: {
        disabledDate (time) {
          return time.getTime() < Date.now() - 8.64e7
        }
      }
    }
  },
  components: {
    ImgUpload,
    detail
  },
  computed: {
    ...mapGetters('zcsd-core', ['permission_projectList']),
    appObjs () {
      return this.permission_projectList.reduce((all, cur) => {
        all[cur.app_id] = cur.name
        return all
      }, {})
    },
    getCurrentTaskType () {
      return (type) => {
        return this.taskTypes[type] || ''
      }
    },
    getCurrentAppName () {
      return (appId) => {
        return this.appObjs[appId] || ''
      }
    },
    getCurrentTaskStatus () {
      return (status) => {
        return this.statusDict[status] || ''
      }
    }
  },
  methods: {
    toDetail (row) {
      this.drawer = true
      this.$nextTick(() => {
        this.currentId = row.group_id
      })
    },
    openTaskDialog (row) {
      if (row) {
        const { stop_at, start_at, task, ...other } = row
        this.form = Object.assign(this.form, {
          ...other,
          time: [parseTime(start_at) || '', parseTime(stop_at)],
          task_id: task.map(item => item.task_id)
        })
      }
      this.dialogVisible = true
    },
    getTaskList (keyword) {
      getTaskList({
        page: 1,
        page_size: 10,
        keyword
      }).then(res => {
        this.taskOptionList = res.data.list
      })
    },
    // 获取列表数据
    getTableList () {
      this.loading = true
      getTaskGroupList(this.queryParams).then(res => {
        this.taskList = res.data.list
        this.total = res.data.count || 0
      }).finally(() => {
        this.loading = false
      })
    },
    // 点击搜索
    handleQuery () {
      this.queryParams.page = 1
      this.getTableList()
    },
    // 重置
    resetQuery () {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    // 新增任务
    addTaskGroup () {
      this.$refs.form.validate((valid) => {
        if (valid) {
          const { time, ...other } = this.form
          const [start_at, stop_at] = time
          const requestParam = {
            ...other,
            ...{
              start_at: +new Date(start_at) / 1000, stop_at: +new Date(stop_at) / 1000
            }
          }
          const apiHandle = this.form.group_id ? updateTaskGroup : addTaskGroup
          apiHandle(requestParam).then(res => {
            this.msgSuccess(this.form.group_id ? '修改任务活动成功' : '新增任务活动成功')
            this.dialogVisible = false
            this.getTableList()
          })
        }
      })
    },
    /** 删除按钮操作 */
    updateTaskGroupStatus (row, status) {
      const id = row.id
      const { page: pageIndex, page_size: pageSize } = this.queryParams
      const operateName = this.statusDict[status]
      const isDelete = status === 'deleted'
      this.$confirm(`是否确认${operateName}该活动？活动名：${row.name}`, isDelete ? '警告' : '提示', {
        type: isDelete ? 'warning' : 'info'
      }).then(() => {
        updateTaskGroup({ id, status }).then(() => {
          this.queryParams.page = this.getCurrentPage({ total: this.total, pageSize, pageIndex })
          this.getTableList()
          this.msgSuccess(`${operateName}成功`)
        })
      })
    },
    reset () {
      this.resetForm('form')
    }
  },
  created () {
    this.handleQuery()
    this.getTaskList()
  }
}
</script>
<style lang="scss" scoped>
.pagination-wrap {
  padding: 20px 0;
}
.add-task-dialog {
  .unit {
    margin-left: 10px;
  }
  .el-col {
    .el-input-number--medium {
      width: 100%;
    }
  }
}
::v-deep .el-drawer__body {
  border-top: 1px solid #ccc;
  padding: 20px;
}
</style>
